package com.ali.memory;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.lang.ref.WeakReference;
import java.nio.ByteBuffer;

import sun.misc.Cleaner;

public class TestPhantomReference2 {
	private static final int ROUND = 1200;
	private ByteBuffer tm, bb;

	private void test() throws Exception {
		BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
		System.out.println("start");
		in.readLine();

		tm = ByteBuffer.allocateDirect(1024 * 100 * 1024);
		// Cleaner cleaner = Cleaner.create(tm, new Deallocator());
		System.out.println("alloc native memory");

		in.readLine();
		// cleaner=null;

		tm = null;
		System.out.println("begin gc");
		for (int i = 0; i < ROUND; i++) {
			bb = ByteBuffer.allocate(1024 * 10 * 10);
			bb = null;
		}
		System.out.println("once gc");

		in.readLine();

		for (int i = 0; i < 800; i++) {
			bb = ByteBuffer.allocate(1024 * 10 * 10);
			bb = null;
		}
		System.out.println("twice gc");

		in.readLine();

	}

	static class Deallocator implements Runnable {

		public void run() {

			System.out.println("cleaner execute! current thread name:"
					+ Thread.currentThread().getName());
		}

	}

	public static void main(String[] args) throws Exception {
		TestPhantomReference2 m = new TestPhantomReference2();
		m.test();
	}
}
